#!/usr/bin/env python3
# usage: python3 clip_single.py <INPUTFILE>
import cv2
import sys
from pathlib import Path
from operator import mod
from tqdm import tqdm

fps = 25

try:
    INPUT_FILE = sys.argv[1]
except:
    INPUT_FILE = 'test.mp4'
    #INPUT_FILE = '201906_81116_1/00000000837000100.mp4'

INPUT_FILE = str(Path(INPUT_FILE).expanduser())
media_name = INPUT_FILE.split('/')[-1].split('.')[0]
media = cv2.VideoCapture(INPUT_FILE)
dataroot = str(Path(INPUT_FILE).parent)

if not Path('add').exists():
    Path('add').mkdir(mode=0o777,parents=False,exist_ok=False)
if not Path('retrieve').exists():
    Path('retrieve').mkdir(mode=0o777,parents=False,exist_ok=False)

_,image = media.read()
shape = image.shape
height = shape[0]
width = shape[1]

try:
    CAMERA_NUM = str(Path(INPUT_FILE).parent).split('/')[-1].split('_')[1]
except:
    try:
        CAMERA_NUM = sys.argv[2]
    except:
        CAMERA_NUM = '000000'

annofile = ''.join([INPUT_FILE,'.anno'])
with open(annofile,'r') as f:
    annodata = f.read().splitlines()
real_time = annodata[0]

real_date,real_start_time = real_time.split('_')
real_start_hour,real_start_min,real_start_sec = real_start_time.split(':')
real_start_hour = int(real_start_hour)
real_start_min = int(real_start_min)
real_start_sec = int(real_start_sec)


outputfiles = []
for index in tqdm(range(1,len(annodata))):
    clipinfo = annodata[index]
    if not clipinfo[0].isdigit():
        video_type = clipinfo
        if video_type == 'add':
            video_type = '1'
            output_path = 'add/'
        else:
            video_type = '0'
            output_path = 'retrieve/'

    else:
        startinfo,endinfo = clipinfo.split('|')
        start_hour,start_min,start_sec = startinfo.split(':')
        start_hour = int(start_hour)
        start_min =  int(start_min)
        start_sec = int(start_sec)


        end_hour,end_min,end_sec = endinfo.split(':')
        end_hour = int(end_hour)
        end_min =  int(end_min)
        end_sec = int(end_sec)

        start_frame = (((start_hour * 60)+start_min)*60+start_sec)*fps
        end_frame = (((end_hour * 60)+end_min)*60+end_sec)*fps
        gap_frame = end_frame - start_frame
        gap_min = int((gap_frame/25)//60)
        gap_sec = int(mod((gap_frame/25),60))
        gap_min = str(gap_min).zfill(2)
        gap_sec = str(gap_sec).zfill(2)
        clip_gap_time = ''.join([gap_min,gap_sec])


        clip_start_sec = real_start_sec + start_sec
        if clip_start_sec >= 60:
            min_plus = clip_start_sec // 60
            clip_start_sec = mod(clip_start_sec,60)
        else:
            min_plus = 0
        clip_start_min = real_start_min + start_min + min_plus
        if clip_start_min >= 60:
            hour_plus = clip_start_min // 60
            clip_start_min = mod(clip_start_min,60)
        else:
            hour_plus = 0
        clip_start_hour = real_start_hour + start_hour + hour_plus
        if clip_start_hour >= 24:
            day_plus = clip_start_hour // 24
            clip_start_hour = mod(clip_start_hour,24)
            real_date = str(int(real_date) + day_plus)

        clip_start_hour = str(clip_start_hour).zfill(2)
        clip_start_min = str(clip_start_min).zfill(2)
        clip_start_sec = str(clip_start_sec).zfill(2)
        



        OUTPUT_FILE = ''.join([output_path,media_name,'-',CAMERA_NUM,'-',real_date,'-',clip_start_hour,clip_start_min,clip_start_sec,'_',clip_gap_time,'-',str(width),'x',str(height),'-',video_type,'.mp4'])
        if Path(OUTPUT_FILE).is_file():
            break

        #print(OUTPUT_FILE)
        outputfiles.append(OUTPUT_FILE)


        start_sec = (start_hour * 60 + start_min) * 60 + start_sec
        end_sec = (end_hour * 60 + end_min) * 60 + end_sec


        start_frame = start_sec * fps
        end_frame = end_sec * fps

        reader = cv2.VideoCapture(INPUT_FILE)
        width = int(reader.get(cv2.CAP_PROP_FRAME_WIDTH))
        height= int(reader.get(cv2.CAP_PROP_FRAME_HEIGHT))

        writer = cv2.VideoWriter(OUTPUT_FILE,
                cv2.VideoWriter_fourcc('m','p','4','v'),
                25,
                (width,height))

        #print(reader.isOpened())
        have_more_frame = True
        c = 0
        while have_more_frame:
            have_more_frame, frame = reader.read()
            c += 1
            if start_frame <= c <= end_frame:
                cv2.waitKey(1)
                writer.write(frame)
                #print(str(c) + ' is ok')
            if c >  end_frame:
                #print("complete")
                break

        writer.release()
        reader.release()
        cv2.destroyAllWindows()

OUTPUT_FILES = [FILE+'\n' for FILE in outputfiles]
with open('output.list','a') as f:
    f.writelines(OUTPUT_FILES)
